import json
import os
import logging

logger = logging.getLogger(__name__)

CONFIG_FILE = 'config.json'

# 默认配置
DEFAULT_CONFIG = {
    'comPort': 'COM3',
    'videoStream': 'http://localhost:8080/?action=snapshot'
}


def load_config():
    """从 config.json 加载配置"""
    try:
        if os.path.exists(CONFIG_FILE):
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                config = json.load(f)
                logger.info(f"✓ 从 {CONFIG_FILE} 加载配置成功")
                return config
        else:
            logger.info(f"{CONFIG_FILE} 不存在，使用默认配置")
            return DEFAULT_CONFIG.copy()
    except Exception as e:
        logger.error(f"✗ 加载配置失败: {e}，使用默认配置")
        return DEFAULT_CONFIG.copy()


def save_config(config):
    """保存配置到 config.json"""
    try:
        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        logger.info(f"✓ 配置已保存到 {CONFIG_FILE}")
        return True
    except Exception as e:
        logger.error(f"✗ 保存配置失败: {e}")
        return False


def get_config():
    """获取当前配置"""
    return load_config()


def update_config(key, value):
    """更新配置中的某个键值"""
    config = load_config()
    config[key] = value
    return save_config(config)


def update_multiple_config(updates):
    """批量更新配置"""
    config = load_config()
    config.update(updates)
    return save_config(config)
